#!/usr/bin/env python
#coding=utf-8

import time
validatelist = ['int', 'double', 'string', 'datetime', 'yn']

class AocBase(object):
    "AOC基类"
    returntype = None
    aocname = 'AocBase'
    
    def __init__(self, aocname, params, user, doc):
        self.aocname = aocname
        self.params = params
        self.doclist = []
        self.user = user
        self.doc = doc
        # 表示该AOC是否成功完成
        self.excutesuccess = False
    
    def excute(self):
        "AOC需要对执行的每一个操作返回是否完成的回应"
        
        # 执行成功标记赋初值，仅当一个aoc实例多次执行时才有意义
        self.excutesuccess = False
        if not self.param_check():
            return None
        self.aoc_parse()
        self.excute_doc()
        
        return self.excutesuccess
    
    def param_check(self):
        "检查参数列表"
        # 对于非交互性途径传入的参数，检查是必要的
        pass
    
    def aoc_parse(self):
        "将该AOC分解为DOC"
        pass
    
    def excute_doc(self):
        "执行该AOC对应的DOC"
        docnum = len(self.doclist)
        docexecsuccess = 0
        if self.doclist:
            for tdoc in self.doclist:
                if self.doc.excute_doc_func(tdoc[0], tdoc[1]):
                    docexecsuccess += 1
        self.user.log.writeLog('exec doc %d tasks, %d success.' % (docnum, docexecsuccess), 'info')
        # 如果全部完成
        if docnum == docexecsuccess:
            self.excutesuccess = True
        else:
            self.excutesuccess = False

def field_validate(data, dtype, dlength=0):
    """AOC数据输入验证静态方法，跟UOC数据验证重复"""
    try:
        validatelist.index(dtype)
    except:
        return None
    if dtype == 'int':
        try:
            data = int(data)
        except:
            return None
        return data
    elif dtype == 'double':
        try:
            data = float(data)
        except:
            return None
        return data
    elif dtype == 'string':
        try:
            if type(data) != type(' '):
                return None
            if len(data) > dlength:
                return None
        except:
            return None
        return data
    elif dtype == 'datetime':
        # datetime 格式为 YYYYMMDDHHMMSS
        # 或者 YYYYMMDD
        # 或者 MMDD
        # 或者 DD
        # 或者 D
        if type(data) != type(' '):
            return None
        if len(data) != 14 and len(data) != 8 and len(data) != 4 and len(data) != 2 and len(data) != 1:
            return None
        t = None
        # 估计此处会出现隐患
        # gmtime 和 localtime，用哪个都不太好
        gt = time.localtime()
        try:
            if len(data) == 14:
                t = time.mktime((int(data[:4]), int(data[4:6]), int(data[6:8]), 
                                 int(data[8:10]), int(data[10:12]), int(data[12:14]),
                                 0, 0, 0))
            elif len(data) == 8:
                t = time.mktime((int(data[:4]), int(data[4:6]), int(data[6:8]), 
                                 0, 0, 0, 0, 0, 0))
            elif len(data) == 4:
                t = time.mktime((gt[0], int(data[:2]), int(data[2:4]), 
                                 0, 0, 0, 0, 0, 0))
            elif len(data) == 2 or len(data) == 1:
                t = time.mktime((gt[0], gt[1], int(data), 
                                 0, 0, 0, 0, 0, 0))
        except:
            return None
        return t
    elif dtype == 'yn':
        try:
            if type(data) != type(' '):
                return None
            if data == 'y' or data == 'Y':
                data = 'y'
            elif data == 'N' or data == 'n':
                data = 'n'
            else:
                return None
        except:
            return None
        return data
    return None

def field_validate_bool(data, dtype, dlength=0):
    """AOC数据输入验证返回True或者False"""
    rslt = field_validate(data, dtype, dlength)
    if not rslt:
        # rslt is None
        return False
    else:
        return True


if __name__ == '__main__':
    # uoc = UocBase('', '', '')
    print field_validate('10', 'int')
    print field_validate('10.1', 'int')
    print field_validate('10.1', 'double')
    print field_validate('5', 'double')
    print field_validate('5e', 'double')
    print field_validate('19860101', 'datetime')
    print field_validate('20050203125635', 'datetime')
    print field_validate('200502031256x5', 'datetime')
    print field_validate('2005020312563', 'datetime')
    
    
    print field_validate_bool('10', 'int')
    print field_validate_bool('10.1', 'int')
    print field_validate_bool('10.1', 'double')
    print field_validate_bool('5', 'double')
    print field_validate_bool('5e', 'double')
    print field_validate_bool('19860101', 'datetime')
    print field_validate_bool('20050203125635', 'datetime')
    print field_validate_bool('200502031256x5', 'datetime')
    print field_validate_bool('2005020312563', 'datetime')
    